import { useState, useEffect, useRef } from "react"

const Counter = () => {
  const [count, setCount] = useState(0)
  const countRef = useRef(count);

  // 直接获取状态的值
  console.log(count)

  useEffect(() => {
    countRef.current = count;
  }, [count]);

  const handleClick = () => {
    setCount(count + 1)
  }

  const getCount = () => {
    setTimeout(() => {
      console.log('延迟获取的count值', count)
      console.log('延迟获取的countRef.current值', countRef.current)
      setCount((state) => {
        console.log('延迟获取的 setCount 的值', state);
        return state + 1
      });
    }, 3000)
  }

  return (
    <div>
      <button onClick={handleClick}>+1</button>
      <button onClick={getCount}>延迟获取 count 值</button>
      <h1>计数器：{count}</h1>
    </div>
  )
}

export default Counter;